package com.example.filter;

import com.alibaba.fastjson.JSON;

import com.example.config.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;



@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String []urls={"/backend/**","/front/**","/employee/login"};
        boolean flag=checkurl(urls,requestURI);
        if (flag){
            filterChain.doFilter(request,response);
            return;
        }
        HttpSession session=request.getSession();
        if (session.getAttribute("employee")!=null){
            filterChain.doFilter(request,response);
            return;
        }




        String json= JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(json);
    }


    private boolean checkurl(String []urls,String requestURI){
        for (String url : urls) {
            if (antPathMatcher.match(url,requestURI)){
                return true;
            }
        }
        return false;
    }

}
